package com.golddaymicromall.application;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Map;
import java.util.logging.Level;


import android.app.Application;
import android.content.Context;

import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.golddaymicromall.util.Log;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.tencent.bugly.crashreport.CrashReport;

import org.apache.http.conn.util.InetAddressUtils;

import cn.jpush.android.api.JPushInterface;
import rx.android.schedulers.AndroidSchedulers;

public class MyApplication extends Application {


    private RefWatcher mRefWatcher;
    private static MyApplication mApplication;
    public static Context ctx;
    String Ip;

    public String GetIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr
                        .hasMoreElements(); ) {
                    InetAddress inetAddress = ipAddr.nextElement();
                    // ipv4地址
                    if (!inetAddress.isLoopbackAddress()
                            && InetAddressUtils.isIPv4Address(inetAddress
                            .getHostAddress())) {

                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (Exception ex) {
        }
        return "";

    }

    @Override
    public void onCreate() {
        mRefWatcher = LeakCanary.install(this);
        mApplication = this;
        super.onCreate();
        ctx = this;
        /*配置bugly*/
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // 初始化Bugly
        CrashReport.initCrashReport(context, "cbe91f917c", true, strategy);


        //初始化
        OkGo.init(this);

        try {
            //全局参数设置
            OkGo.getInstance()
                    //打开调试开关
                    .debug("jtmarket", Level.INFO, true)
                    //如果使用默认的 60秒
                    .setConnectTimeout(120000)
                    .setReadTimeOut(120000)
                    .setWriteTimeOut(120000)
                    .setRetryCount(3)
                    //可以全局统一设置缓存模式,默认是不使用缓存
                    .setCacheMode(CacheMode.NO_CACHE)
                    //可以全局统一设置缓存时间,默认永不过期
                    .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE);
        } catch (Exception e) {
            e.printStackTrace();
        }

        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush

    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    //单例
    public static synchronized MyApplication getInstance() {
        return mApplication;
    }

    //服务端添加日志
    public void attemptRiZhi(String Customerno, String massage) {
        Ip = GetIp().toString();
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.Loginfo.save");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("ipAddress", Ip);
        form.put("message", "A-" + massage);
        form.put("username", Customerno);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    Log.e("Customerno", "A-" + massage);
                }, throwable -> {
                    throwable.printStackTrace();
                });
    }

}
